package com.example.landlord.demo.utils.system;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Collection;

//处理用户操作信息
public class UserHandle extends Thread {
    MyWebSocketServer myWebSocketServer;
    WebSocketMessage webSocketMessage;

    public UserHandle(WebSocketMessage webSocketMessage,MyWebSocketServer myWebSocketServer){
        this.webSocketMessage = webSocketMessage;
        this.myWebSocketServer = myWebSocketServer;
        System.out.println("用户进入服务器");
    }

    @Override
    public void run() {
        super.run();
        User user = myWebSocketServer.userCollection.getUserBySocket(webSocketMessage.webSocket);
        switch (webSocketMessage.order){
            case 0:
                myWebSocketServer.userCollection.addUser(webSocketMessage);
                ObjectMapper objectMapper = new ObjectMapper();
                ObjectNode objectNode=objectMapper.createObjectNode();
                objectNode.put("order",10);
                objectNode.put("result",true);
                try{
                    webSocketMessage.webSocket.send(objectMapper.writeValueAsString(objectNode));
                    System.out.println("发送了认证结果");
                }catch (JsonProcessingException e){
                    e.printStackTrace();
                }
                System.out.println("当前在线人数为:"+myWebSocketServer.userCollection.getUsers().size());
                break;
            case 1:     //玩家对游戏的操纵消息

                break;
            case 2: //创建游戏
                createGame();
                break;
            case 3: //对游戏进行操作
                gameOperation();
                break;
            case 4://玩家请求指定游戏的所有房间
                getRoomList(false);
                break;
            case 5:
                getRoomByUser(user);
                break;
            case 6://玩家请求自己是否处于游戏状态
                getGameStatusByUser(user);
                break;
            case 7: //查询游戏进展
//                System.out.println("roomId:"+webSocketMessage.roomId);
//                System.out.println("name:"+webSocketMessage.name);
                myWebSocketServer.getLandlordByRoomId(webSocketMessage.roomId).getGameProcessing(webSocketMessage);
                break;
            case 8: //查询当前由谁叫分
                myWebSocketServer.getLandlordByRoomId(webSocketMessage.roomId).getScoreByPlayer(webSocketMessage);
                break;
            case 9:
                myWebSocketServer.getLandlordByRoomId(webSocketMessage.roomId).getPuckerByPlayer(webSocketMessage.webSocket);
                break;
        }
    }

    public void getGameStatusByUser(User user){
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode result = objectMapper.createObjectNode();
        boolean start = user.game!=null&&user.game.getGameStatus()==GameStatus.STARTED;
        result.put("order",6);
        result.put("result",start);
        if(start){
            int gameType=0;
            switch (user.game.gameType){
                case LANDLORD:
                    gameType=1;
                    break;
            }
            result.put("game",gameType);
        }
        try{
            webSocketMessage.webSocket.send(objectMapper.writeValueAsString(result));
        }catch (JsonProcessingException e){}

    }

    public void getRoomByUser(User user){
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode result = objectMapper.createObjectNode();
        result.put("order", 5);
        if(user.gameType==GameType.NOGAME){
            result.put("gameType", 0);
            try{
                webSocketMessage.webSocket.send(objectMapper.writeValueAsString(result));
            }catch (JsonProcessingException e){}
            return;
        }
        result.put("gameType", 1);
        result.put("roomId", user.game.id);
        result.put("roomName", user.game.name);
        result.put("created", user.game.createdPlayer.user.id);
        ArrayNode arrayNode = objectMapper.createArrayNode();
        for(Player p : user.game.players){
            ObjectNode o = objectMapper.createObjectNode();
            o.put("id",p.user.id);
            o.put("ready",p.ready);
            arrayNode.add(o);
        }
        result.put("players", arrayNode);
        try{
            webSocketMessage.webSocket.send(objectMapper.writeValueAsString(result));
        }catch (JsonProcessingException e){}
    }

    public void getRoomList(boolean broadcast){
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayNode arrayNode = objectMapper.createArrayNode();
        ObjectNode result = objectMapper.createObjectNode();
        switch (webSocketMessage.game){
            case 1:
                //斗地主游戏列表
                for(LandLord l : myWebSocketServer.landlordList){
                    ObjectNode o = objectMapper.createObjectNode();
                    o.put("roomName", l.name);
                    o.put("created", l.createdPlayer.user.id);
                    o.put("num", l.players.size());
                    o.put("roomId", l.id);
                    arrayNode.add(o);
                }
                result.put("order", 4);
                result.put("list", arrayNode);
                break;
        }

        try{
            String json = objectMapper.writeValueAsString(result);
            if(broadcast){
                //广播发送
                Collection<User> userCollection = myWebSocketServer.userCollection.getUsers();
                for(User u : userCollection){
                    try{
                        u.webSocket.send(json);
                    }catch (Exception e){
                        System.out.println("广播房间列表出现了问题，问题用户:"+u.name);
                        continue;
                    }
                }
            }else{
                webSocketMessage.webSocket.send(json);
            }
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
    }

    public void createGame(){
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode json = objectMapper.createObjectNode();
        json.put("roomId","");
        switch (webSocketMessage.game){
            case 0:
                System.out.println("创建了斗地主游戏");
                json.put("order",0);
                LandLord l = createLandlord();
                json.put("roomId", l.id);
                json.put("roomName", l.name);
                getRoomList(true);
                break;
        }
        try{
            webSocketMessage.webSocket.send(objectMapper.writeValueAsString(json));
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
    }

    //返回房间编号
    public synchronized LandLord createLandlord(){
        LandLord landLord = new LandLord(myWebSocketServer);
        landLord.name = webSocketMessage.name;
        //创建者自动进入该游戏
        User user = myWebSocketServer.userCollection.getUserBySocket(webSocketMessage.webSocket);
        landLord.addPlayer(new Player(user));
        myWebSocketServer.landlordList.add(landLord);
        webSocketMessage.game=1;
        getRoomList(true);
        return landLord;
    }

    public void gameOperation(){
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode json = objectMapper.createObjectNode();
        json.put("order",2);
        boolean result =false;
        Player player= new Player(myWebSocketServer.userCollection.getUserBySocket(webSocketMessage.webSocket));
        switch (webSocketMessage.game){
            case 1:
                //斗地主类型
                LandLord landLord=myWebSocketServer.getLandlordByRoomId(webSocketMessage.roomId);
                if(landLord==null){System.out.println("landlord is null");break;}
                switch (webSocketMessage.mode){
                    case 0:
//                        System.out.println("b");
                        //对房间玩家的操作
                        if(webSocketMessage.operation==0){
                            //加入房间
                            if(landLord.addPlayer(player)){
                                //操作房间成功
                                result=true;
                                break;
                            }
                        }else{
                            if(landLord.removePlayer(player)){
                                result=true;
                                //检查如果当前游戏一个玩家都没有了，就销毁这个游戏
                                if(landLord.players.size()==0){
                                    System.out.println(landLord.id+"房间因为没有一个玩家，因此将其销毁");
//                                    myWebSocketServer.landlordList.remove(landLord);
//                                    landLord=null;
                                    landLord.delGame();

                                }
                                break;
                            }
                        }
                        break;
                    case 1:
                        //游戏开始操作
//                        System.out.println("玩家准备");
                        result=landLord.startGame(webSocketMessage.webSocket);
                        break;
                    case 2:
//                        System.out.println("c");
                        //游戏操作命令
                        switch (webSocketMessage.cmd) {
                            case 0:
                                //出牌操作
                                result = landLord.gameDoing(webSocketMessage);
                                json.put("result", result);
                                json.put("order", 3);
                                json.put("mode", 1);
                                if (result) {
                                    //成功出牌后，通知游戏中所有玩家
                                    json.put("index", landLord.getPlayerBySocket(webSocketMessage.webSocket).index);//当前出牌的玩家，包括没有出牌的玩家
                                    json.put("lastIndex", landLord.lastPuckerStep.player.index);//上一次出牌的玩家
                                    json.put("pokerDefine", landLord.lastPuckerStep.definePucker.getValue());//出牌类型
                                    json.put("nextIndex", landLord.currentIndex);//下一个出牌的玩家
                                    json.put("noSend", landLord.noSend);
//                                    json.put("newTurn",landLord.flag);//是否为新的一轮出牌
                                    ArrayNode list = objectMapper.createArrayNode();
                                    if (landLord.lastPokers != null) {
                                        for (int id : landLord.lastPokers) {
                                            ObjectNode objectNode = objectMapper.createObjectNode();
                                            objectNode.put("name", landLord.puckerSystem.pukerList[id].pName);
                                            objectNode.put("value", landLord.puckerSystem.pukerList[id].value);
                                            objectNode.put("id", landLord.puckerSystem.pukerList[id].id);
                                            objectNode.put("color", landLord.puckerSystem.pukerList[id].color);
                                            objectNode.put("sended", landLord.puckerSystem.pukerList[id].status == PuckerStatus.NOTSEND ? false : true);
                                            list.add(objectNode);
                                        }
                                    }
                                    json.put("idList", list);
                                    for (Player p : landLord.players) {
                                        if (p.user.webSocket == webSocketMessage.webSocket) {
                                            continue;
                                        }
                                        try {
                                            p.user.webSocket.send(objectMapper.writeValueAsString(json));
                                        } catch (JsonProcessingException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                } else {
                                    //出牌失败
                                    landLord.sendMessage(webSocketMessage.webSocket, json);
                                }
                                break;
                            case 1:
                                result = landLord.speakScore(webSocketMessage);
                                break;

                        }
                        break;
                    case 3:
                        //房间聊天消息处理
                        landLord.appendChatMessage(webSocketMessage);
                        break;
                    case 4:
                        landLord.setPlayerRead(webSocketMessage);
                        break;
                    case 5:
//                        System.out.println("玩家想要获取消息列表");
                        landLord.getChatMessage(webSocketMessage.webSocket);
                        break;
                    case 6:
                        landLord.noticeTimes(landLord.getPlayerBySocket(webSocketMessage.webSocket));
                        break;
                }
                break;
        }
        json.put("result", result);
        try{
            webSocketMessage.webSocket.send(objectMapper.writeValueAsString(json));
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
    }
}
